//
//  YWMyAttendanceViewController.m
//  maintain
//
//  Created by Kyo on 16/4/18.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWMyAttendanceViewController.h"
#import "UIColor+CustomColors.h"
#import "UIView+Extension.h"
#import "YWMacro.h"
#import "YWConst.h"
#import "YWCommonTool.h"
#import "YWLocationManager.h"
#import <AMapLocationKit/AMapLocationKit.h>
#import "YWAttendanceRecord.h"
#import "YWAttendanceManager.h"
#import "NSDate+Additions.h"
#import "YWNoQrcodeRights.h"
#import "YWLoginTool.h"

#import "QRCodeReaderViewController.h"
#import "YWAttendanceViewController.h"
#import "YWNavigationController.h"
#import "YWQrcodeManager.h"
#import "YWAttendanceRecordTableViewCell.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "YWAttendanceRecordDetailTableViewController.h"
#import "MJRefresh.h"
#import "YWNoQrcodeSelectLocationTableViewController.h"

#define kRecordDicTitle @"title"
#define kRecordDicRecord @"records"

@interface YWMyAttendanceViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic, weak) UIView* headView;
@property (nonatomic, weak) UIImageView* locationIV;
@property (nonatomic, weak) UILabel* locationLabel;

@property (nonatomic, weak) UILabel* dateLabel;
@property (nonatomic, weak) UILabel* timeLabel;

@property (nonatomic, strong) NSTimer* timer;
@property (nonatomic, strong) NSDateFormatter* dateFormatter;

@property (nonatomic, strong) UIButton *scanButton;
@property (nonatomic, strong) UIButton *noScanButton;

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray* dataSources;

@property (nonatomic, assign) NSInteger page;
@end

@implementation YWMyAttendanceViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = NSLocalizedString(@"arrive", nil);//@"签到";
    self.view.backgroundColor = [UIColor customBackgroudColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"签到记录" style:UIBarButtonItemStylePlain target:self action:@selector(attendanceRecordEvent:)];
    self.page =1;
    self.headView.backgroundColor = [UIColor whiteColor];
    self.tableView.backgroundColor = [UIColor customBackgroudColor];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshTop)];
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(refreshFootor)];
    self.tableView.mj_footer.automaticallyHidden = YES;
    // 马上进入刷新状态
    [self.tableView.mj_header beginRefreshing];

    [self.view addSubview:self.noScanButton];
    [self.view addSubview:self.scanButton];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateAttendanceUploadStatus) name:KUpdateAttendanceUploadStatusNotification object:nil];
    
    [self setDateLabelAndTimeLabel];
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];
    
    [self location];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)refreshTop
{
    self.page = 1;
    [self.tableView.mj_footer resetNoMoreData];
    [self requestData:YWTableViewFreshTypeDown];
}

- (void)refreshFootor
{
    [self requestData:YWTableViewFreshTypeUp];
    //    self.page++;
    //    _dataSources = nil;
    //    [self.tableView.mj_footer endRefreshing];
    //    [self.tableView reloadData];
}

- (void)requestData:(YWTableViewFreshType)refreshType
{
    YWWeakSelf(weakSelf);
    if (refreshType == YWTableViewFreshTypeUp) {
        weakSelf.page++;
    }
    [[YWAttendanceManager shareManager] getAboutMeAttendanceWithPage:weakSelf.page pageSize:10 WithComplete:^(BOOL success) {
        if (refreshType == YWTableViewFreshTypeDown) {
            [weakSelf.tableView.mj_header endRefreshing];
        }else {
            [weakSelf.tableView.mj_footer endRefreshing];
        }
        if (success) {
            weakSelf.dataSources = nil;
            [weakSelf.tableView reloadData];
        }
    }];
}

- (NSArray*)dataSources
{
    if (!_dataSources) {
        NSMutableArray* dataSources = [NSMutableArray array];
        NSArray* allRecords = [[YWAttendanceManager shareManager] attendanceRecordWithPage:self.page];
        for (YWAttendanceRecord* attendanceRecord in allRecords) {
            BOOL sameYearMonth = NO;
            for (NSMutableDictionary* showDic in dataSources) {
                if ([[showDic objectForKey:kRecordDicTitle] integerValue] == attendanceRecord.yearMonthDay) {
                    NSMutableArray* records = [NSMutableArray arrayWithArray:[showDic objectForKey:kRecordDicRecord]];
                    [records addObject:attendanceRecord];
                    [showDic setObject:records forKey:kRecordDicRecord];
                    sameYearMonth = YES;
                    break;
                }
            }
            if (!sameYearMonth) {
                NSMutableDictionary* showDic = [NSMutableDictionary dictionary];
                [showDic setObject:@(attendanceRecord.yearMonthDay) forKey:kRecordDicTitle];
                NSArray* array = [NSArray arrayWithObject:attendanceRecord];
                [showDic setObject:array forKey:kRecordDicRecord];
                [dataSources addObject:showDic];
            }
        }
        _dataSources = dataSources;
    }
    return _dataSources;
}

#pragma mark - UITableViewDataSource mothods
//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    return [tableView fd_heightForCellWithIdentifier:YWAttendanceRecordTableViewCellIdentifier cacheByIndexPath:indexPath configuration:^(YWAttendanceRecordTableViewCell *cell) {
//        cell.fd_enforceFrameLayout = NO;
//        NSDictionary* record = self.dataSources[indexPath.section];
//        NSArray* records = [record objectForKey:kRecordDicRecord];
//        cell.attendanceRecord = records[indexPath.row];
//    }];
//}

- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView
{
    return self.dataSources.count;
}

- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
{
    NSDictionary* record = self.dataSources[section];
    NSArray* records = [record objectForKey:kRecordDicRecord];
    return records.count;
}

- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
    NSDictionary* record = self.dataSources[indexPath.section];
    YWAttendanceRecordTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:YWAttendanceRecordTableViewCellIdentifier];
    cell.fd_enforceFrameLayout = NO;

    NSArray* records = [record objectForKey:kRecordDicRecord];
    cell.attendanceRecord = records[indexPath.row];
    return cell;
}

- (NSString*)tableView:(UITableView*)tableView titleForHeaderInSection:(NSInteger)section
{
    NSDictionary* record = self.dataSources[section];
//    NSInteger yearMonthDay = [[record objectForKey:kRecordDicTitle] integerValue];
    NSArray* records = [record objectForKey:kRecordDicRecord];
    YWAttendanceRecord *attendanceRecord = records[0];
    NSString* title = [NSString stringWithFormat:@"%ld年%@", (long)(attendanceRecord.yearMonthDay / 10000), attendanceRecord.dateShow];
//    NSMutableString *title = [NSMutableString stringWithFormat:@"%ld",(long)yearMonthDay];
//    if (title.length>=4) {
//        [title insertString:@"年" atIndex:4];
//    }
//    if (title.length>=7) {
//        [title insertString:@"月" atIndex:7];
//    }
//    if (title.length>=10) {
//        [title insertString:@"日" atIndex:10];
//    }
//    NSString* title = [NSString stringWithFormat:@"%ld年%.2ld月", yearMonth / 100, yearMonth % 100];
    return title;
}
#pragma mark - UITableViewDelegate mothods
- (CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}

- (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    YWAttendanceRecordDetailTableViewController* vc = [[YWAttendanceRecordDetailTableViewController alloc] init];
    NSDictionary* record = self.dataSources[indexPath.section];
    NSArray* records = [record objectForKey:kRecordDicRecord];
    vc.attendanceRecord = records[indexPath.row];
    [self.navigationController pushViewController:vc animated:YES];
}

- (UIView*)headView
{
    if (!_headView) {
        UIView* headView = [[UIView alloc] init];
        [self.view addSubview:headView];
        _headView = headView;
        
        CGFloat smallIconSize = 17;
        [self.locationIV setFrame:CGRectMake(kMarginW, kGapH, smallIconSize, smallIconSize)];
        CGFloat locationW = SCREEN_WIDTH - CGRectGetMaxX(self.locationIV.frame) - 3 - kMarginW;
        CGFloat locationH = [YWCommonTool getHeightOfLabel:self.locationLabel.text andWidth:locationW andFont:self.locationLabel.font andMinHeight:kLabelH];
        [self.locationLabel setFrame:CGRectMake(CGRectGetMaxX(self.locationIV.frame) + 3, kGapH, locationW, locationH)];
        [self.dateLabel setFrame:CGRectMake(0, CGRectGetMaxY(self.locationLabel.frame) + kGapH * 2, SCREEN_WIDTH, kLabelH)];
        [self.timeLabel setFrame:CGRectMake(0, CGRectGetMaxY(self.dateLabel.frame) + kGapH * 2, SCREEN_WIDTH, kLabelH)];
        
        CGFloat totalH = kGapH + locationH + kGapH * 4 + kLabelH * 2 + kGapH;
        [_headView setFrame:CGRectMake(0, 0, SCREEN_WIDTH, totalH)];
    }
    return _headView;
}
- (UITableView *)tableView{
    if (!_tableView) {
        UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.headView.frame), SCREEN_WIDTH, SCREEN_HEIGHT - 64 -CGRectGetMaxY(self.headView.frame) - KbottomViewH) style:UITableViewStylePlain];
        [tableView registerClass:[YWAttendanceRecordTableViewCell class] forCellReuseIdentifier:YWAttendanceRecordTableViewCellIdentifier];
        tableView.dataSource = self;
        tableView.delegate = self;
        tableView.separatorColor = [UIColor customLineColor];
        tableView.tableFooterView = [[UIView alloc] init];
        tableView.estimatedRowHeight = 44.0f;
        tableView.rowHeight = UITableViewAutomaticDimension;
        [self.view addSubview:tableView];
        _tableView = tableView;
    }
    return _tableView;
}

- (UIImageView*)locationIV
{
    if (!_locationIV) {
        UIImageView* locationImageV = [[UIImageView alloc] init];
        locationImageV.image = [UIImage imageNamed:@"common_location"];
        [_headView addSubview:locationImageV];
        _locationIV = locationImageV;
    }
    return _locationIV;
}

- (UILabel*)locationLabel
{
    if (!_locationLabel) {
        UILabel* locationLabel = [[UILabel alloc] init];
        locationLabel.font = kContentFont;
        locationLabel.numberOfLines = 2;
        [_headView addSubview:locationLabel];
        _locationLabel = locationLabel;
    }
    return _locationLabel;
}

- (UILabel*)dateLabel
{
    if (!_dateLabel) {
        UILabel* dateLabel = [[UILabel alloc] init];
        dateLabel.font = kContentFont;
        dateLabel.textAlignment = NSTextAlignmentCenter;
        [_headView addSubview:dateLabel];
        _dateLabel = dateLabel;
    }
    return _dateLabel;
}

- (UILabel*)timeLabel
{
    if (!_timeLabel) {
        UILabel* timeLabel = [[UILabel alloc] init];
        timeLabel.font = [UIFont boldSystemFontOfSize :20];
        timeLabel.textAlignment = NSTextAlignmentCenter;
        [_headView addSubview:timeLabel];
        _timeLabel = timeLabel;
    }
    return _timeLabel;
}

- (NSTimer*)timer
{
    if (!_timer) {
        NSTimer* timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
        _timer = timer;
    }
    return _timer;
}

- (NSDateFormatter*)dateFormatter
{
    if (!_dateFormatter) {
        _dateFormatter = [[NSDateFormatter alloc] init];
        [_dateFormatter setDateFormat:@"yyyy年MM月dd日 HH:mm:ss"];
    }
    return _dateFormatter;
}


- (UIButton *)scanButton{
    if (!_scanButton) {
        UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
//        [button setImage:[UIImage imageNamed:@"attendance_normal"] forState:UIControlStateNormal];
//        button.layer.masksToBounds = YES;
        [button setTitle:NSLocalizedString(@"scanQrcode", nil) forState:UIControlStateNormal];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        button.backgroundColor = [UIColor customBlueColor];
        [button addTarget:self action:@selector(handleScanButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
        button.frame = CGRectMake(SCREEN_WIDTH/4, SCREEN_HEIGHT-64-KbottomViewH, SCREEN_WIDTH/4*3, KbottomViewH);
        _scanButton = button;
    }
    return _scanButton;
}
- (UIButton *)noScanButton{
    if (!_noScanButton) {
        UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setTitle:NSLocalizedString(@"noQrcode", nil) forState:UIControlStateNormal];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        button.backgroundColor = [UIColor customYellowColor];
        [button addTarget:self action:@selector(handleNoScanBtnEvent:) forControlEvents:UIControlEventTouchUpInside];
        button.frame = CGRectMake(0, SCREEN_HEIGHT-64-KbottomViewH, SCREEN_WIDTH/4, KbottomViewH);
        _noScanButton = button;
    }
    return _noScanButton;
}

-(void)handleScanButtonEvent:(id)sender{
    [[YWQrcodeManager shareManager] clickScanButtonWithType:YWQrcodeScanTypeNomall ViewController:self completionBlock:^(NSString *qrcodeId, QRCodeReaderViewController *qrCodeReaderViewController) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [qrCodeReaderViewController dismissViewControllerAnimated:NO completion:^{
                YWAttendanceViewController* attendanceVC = [[YWAttendanceViewController alloc] init];
                attendanceVC.qrcodeId = qrcodeId;
                [self.navigationController pushViewController:attendanceVC animated:YES];
            }];
        });
    }];
}

- (void)handleNoScanBtnEvent:(id)sender{
    YWAttendanceViewController* attendanceVC = [[YWAttendanceViewController alloc] init];
    [self.navigationController pushViewController:attendanceVC animated:YES];
    /*
    NSInteger value = [[[NSUserDefaults standardUserDefaults] objectForKey:KYWNoQrcodeTypeAttendanceKey] integerValue];
    if (value==1) {
        UIAlertController* alertController= [UIAlertController alertControllerWithTitle:@"无码工作已被管理员禁止" message:nil preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
        [self presentViewController:alertController animated:YES completion:nil];
    }else{
        YWNoQrcodeSelectLocationTableViewController *noQrcodeSlecetLocationVC = [[YWNoQrcodeSelectLocationTableViewController alloc] init];
        __weak __typeof(&*noQrcodeSlecetLocationVC) weakNoQrcodeSlecetLocationVC = noQrcodeSlecetLocationVC;
        noQrcodeSlecetLocationVC.isDoTempMission = NO;
        noQrcodeSlecetLocationVC.doMissionBlock = ^(NSInteger locationId) {
            __strong __typeof(&*weakNoQrcodeSlecetLocationVC) strongNoQrcodeSlecetLocationVC = weakNoQrcodeSlecetLocationVC;
            YWAttendanceViewController* attendanceVC = [[YWAttendanceViewController alloc] init];
            attendanceVC.locationId = locationId;
            [strongNoQrcodeSlecetLocationVC.navigationController pushViewController:attendanceVC animated:YES];
        };
        [self.navigationController pushViewController:noQrcodeSlecetLocationVC animated:YES];
    }*/
}

- (void)updateAttendanceUploadStatus{
    dispatch_async(dispatch_get_main_queue(), ^{
        _dataSources = nil;
        [self.tableView reloadData];
    });
}

-(void)dealloc{
    [self.timer invalidate];
    self.timer = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)setDateLabelAndTimeLabel
{
    NSString* dateTime = [self.dateFormatter stringFromDate:[NSDate date]];
    NSArray* array = [dateTime componentsSeparatedByString:@" "];
    if (array.count == 2) {
        if (![self.dateLabel.text isEqualToString:array[0]]) {
            self.dateLabel.text = array[0];
        }
        self.timeLabel.text = array[1];
    }
}

- (void)timerAction
{
    [self setDateLabelAndTimeLabel];
}

- (void)location
{
    self.locationLabel.text = NSLocalizedString(@"noPosition", nil);//@"暂无定位";
    //[[YWLocationManager shareManager] setUpLocationAccuracy:kCLLocationAccuracyHundredMeters];
    BOOL enable = [CLLocationManager locationServicesEnabled];
    int status = [CLLocationManager authorizationStatus];
    if ( enable && ( status == kCLAuthorizationStatusAuthorizedWhenInUse)) {
        self.locationLabel.text = NSLocalizedString(@"positioning", nil);//@"正在定位中...";
        [[YWLocationManager shareManager] locationInfoWithCompletionBlock:^(NSString* locationInfo, NSError* error, CLLocation* location) {
            CGFloat locationW = SCREEN_WIDTH - CGRectGetMaxX(self.locationIV.frame) - 3 - kMarginW;
            CGFloat locationH = [YWCommonTool getHeightOfLabel:locationInfo andWidth:locationW andFont:self.locationLabel.font andMinHeight:kLabelH];
            if (locationH>kLabelH && locationH<kLabelH*2) {
                self.locationLabel.height = locationH;
            }else if (locationH > kLabelH*2){
                self.locationLabel.height = kLabelH*2;
            }
            self.locationLabel.text = locationInfo;
            
        }];
    }
    else if (status == kCLAuthorizationStatusDenied) {
        self.locationLabel.text = NSLocalizedString(@"accessLocationsAreNotAllowed", nil);//@"不允许访问位置信息";
    }
    else if (!iOS8 && (!enable || status<3)){
        [[YWLocationManager shareManager] locationInfoWithCompletionBlock:^(NSString* locationInfo, NSError* error, CLLocation* location) {
            self.locationLabel.text = locationInfo;
        }];
    }
}
@end
